//
//  TimeRedPacketView.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/4.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class TimeRedPacketView: UIView {
    var redBlock:(() -> Void)?
    var newfunction:UIImageView = UIImageView.init()
    var viewName:String = ""
    var state:Int = 0
    var price:NSNumber = 0.0
    
    init(frame: CGRect, viewName:String) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
        self.viewName = viewName
        setUI()
        setData()

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI() {
        self.isUserInteractionEnabled = true
        newfunction.frame = CGRect(x:0, y:0, width:80, height:80)
        let arr = NSMutableArray()
        let image1 = UIImage.init(named: "newFunction1")
        let image2 = UIImage.init(named: "newFunction2")
        arr.addObjects(from: [image1 as Any, image2 as Any])
        newfunction.animationImages = arr as? [UIImage]
        newfunction.animationDuration = 1
        newfunction.isHidden = true
        newfunction.startAnimating()
        self.addSubview(newfunction)
        newfunction.isUserInteractionEnabled = true
        newfunction.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(redAction)))
    }
    
    func setData() {
        HomeRequestModel.loadRandomData(parameters: [UserId:String.getUserId(),"pageConfig":self.viewName]) { (success, message, state, price) in
            if success {
                self.state = state
                self.price = price
                self.newfunction.isHidden = false
            } else {
                self.newfunction.isHidden = true
                self.removeFromSuperview()
            }
        }
    }
    
    @objc func redAction() {
        HomeRequestModel.loadSavetbData(parameters: [UserId:String.getUserId(),"state":self.state]) { (success, message) in
            if success {
                self.newfunction.isHidden = true
                self.removeFromSuperview()
                let next = TimeRedNextView.init(frame: FRAME_CGFloat(0, OFFSET_TOP, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP), priceStr: String.money(self.price) ?? "0")
                next.redBlock = { () in
                    let vc = TBWithdrawVc()
                    PUSHVIEWCONTROLLER(vc)
                }
                UIApplication.shared.keyWindow?.addSubview(next)
            }
        }
        
    }

}
